from django.core.files.storage import default_storage
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework import permissions, authentication
from rest_framework_simplejwt.authentication import JWTAuthentication

from .serializers import UploadImageSerializer


class UploadImageGenericAPIView(GenericAPIView):
    """ 上传图片 """

    serializer_class = UploadImageSerializer
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = [
        authentication.SessionAuthentication, 
        JWTAuthentication
    ]

    def post(self, request, *args, **kwargs):
        """ 上传图片 """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        file = serializer.validated_data['image']
        # 这里为我们执行了上传图片的操作
        name = default_storage.save(file.name, file)
        # 这个request不是django原生的request，而是rest_framework的request
        url = request.build_absolute_uri(default_storage.url(name))
    
        return Response({
            'code': 'ok',
            'url': url,
            'text': file.name
        })